<template>
  <div class="patent-management-container">
    <!-- 搜索区域：仅管理员和审核员可见 -->
    <el-card v-if="!isTeacher" class="search-card">
      <div class="search-header">
        <h2>专利管理</h2>
        <el-button type="primary" @click="handleAddPatent">添加专利</el-button>
      </div>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="教师姓名">
          <el-input v-model="searchForm.teacherName" placeholder="请输入教师姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="专利名称">
          <el-input v-model="searchForm.name" placeholder="请输入专利名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="专利类型">
          <el-select v-model="searchForm.type" placeholder="请选择专利类型" clearable style="width: 120px;">
            <el-option v-for="item in patentTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="授权号">
          <el-input v-model="searchForm.authorizationNumber" placeholder="请输入授权号" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 教师视图：简化的头部 -->
    <el-card v-if="isTeacher" class="search-card">
      <div class="search-header">
        <h2>我的专利</h2>
        <el-button type="primary" @click="handleAddPatent">添加专利</el-button>
      </div>
    </el-card>

    <!-- 专利列表 -->
    <el-card class="list-card">
      <el-table 
        :data="patentList" 
        style="width: 100%" 
        v-loading="loading" 
        border
      >
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="teacherName" label="教师姓名" min-width="100" v-if="!isTeacher"></el-table-column>
        <el-table-column prop="name" label="专利名称" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="type" label="专利类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getPatentTypeTag(scope.row.type)">{{ getPatentTypeText(scope.row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="authorizationNumber" label="授权号" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="authorizationDate" label="授权日期" width="120" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="handleEditPatent(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeletePatent(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑专利对话框 -->
    <el-dialog 
      :title="dialogType === 'add' ? '添加专利' : '编辑专利'" 
      v-model="dialogVisible" 
      width="600px"
    >
      <el-form 
        :model="patentForm" 
        :rules="patentFormRules" 
        ref="patentFormRef" 
        label-width="100px"
      >
        <el-form-item label="教师" prop="teacherId" v-if="!isTeacher">
          <el-select v-model="patentForm.teacherId" placeholder="请选择教师" filterable style="width: 100%">
            <el-option 
              v-for="teacher in teacherOptions" 
              :key="teacher.id" 
              :label="teacher.realName + ' (' + teacher.department + ')'" 
              :value="teacher.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专利名称" prop="name">
          <el-input v-model="patentForm.name" placeholder="请输入专利名称"></el-input>
        </el-form-item>
        <el-form-item label="专利类型" prop="type">
          <el-select v-model="patentForm.type" placeholder="请选择专利类型" style="width: 100%">
            <el-option v-for="item in patentTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="授权号" prop="authorizationNumber">
          <el-input v-model="patentForm.authorizationNumber" placeholder="请输入授权号"></el-input>
        </el-form-item>
        <el-form-item label="授权日期" prop="authorizationDate">
          <el-date-picker v-model="patentForm.authorizationDate" type="date" placeholder="选择授权日期" style="width: 100%" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select 
            v-model="patentForm.status" 
            placeholder="请选择状态" 
            style="width: 100%"
            :disabled="isTeacher">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <div v-if="isTeacher" class="status-note">
            <small>注：教师提交的专利默认为待审核状态</small>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPatentForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '../stores/user'

// 获取用户信息
const userStore = useUserStore()
const userRole = computed(() => userStore.userRole || localStorage.getItem('userRole'))
const isTeacher = computed(() => userRole.value === 'teacher')
const currentTeacherId = ref(null)

// 修改专利类型选项
const patentTypeOptions = [
  { value: 'invention', label: '发明专利' },
  { value: 'utility_model', label: '实用新型' }
]

// 修改获取专利类型文本的函数
const getPatentTypeText = (type) => {
  const typeMap = {
    'invention': '发明专利',
    'utility_model': '实用新型'
  }
  return typeMap[type] || type
}

// 修改获取专利类型标签的函数
const getPatentTypeTag = (type) => {
  const typeMap = {
    'invention': 'danger',
    'utility_model': 'warning'
  }
  return typeMap[type] || 'info'
}

// 状态选项
const statusOptions = [
  { value: 'pending', label: '待审核' },
  { value: 'approved', label: '已通过' },
  { value: 'rejected', label: '已拒绝' }
]


// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

// 搜索表单
const searchForm = reactive({
  teacherName: '',
  name: '',
  type: '',
  authorizationNumber: '',
  status: ''
})

// 专利列表数据
const patentList = ref([])
const loading = ref(false)

// 教师选项
const teacherOptions = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const patentFormRef = ref(null)
const submitLoading = ref(false)

// 专利表单
const patentForm = reactive({
  id: null,
  teacherId: '',
  name: '',
  type: '',
  authorizationNumber: '',
  authorizationDate: '',
  status: 'pending'
})

// 专利表单验证规则
const patentFormRules = {
  teacherId: [
    { required: true, message: '请选择教师', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入专利名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择专利类型', trigger: 'change' }
  ],
  authorizationNumber: [
    { required: true, message: '请输入授权号', trigger: 'blur' }
  ],
  authorizationDate: [
    { required: true, message: '请选择授权日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取当前教师ID
const fetchCurrentTeacherId = async () => {
  try {
    // 从localStorage获取user并解析JSON
    let userId = userStore.userId
    if (!userId) {
      const userStr = localStorage.getItem('user')
      if (userStr) {
        try {
          const userObj = JSON.parse(userStr)
          userId = userObj.id
        } catch (e) {
          console.error('解析用户信息错误:', e)
        }
      }
    }
    
    if (userId) {
      const response = await axios.get(`http://localhost:8081/api/teacher/getByUserId?userId=${userId}`)
      if (response.data.code === 200 && response.data.data) {
        // 从返回的数据中获取教师ID
        currentTeacherId.value = response.data.data.teacher.id
        console.log('获取到教师ID:', currentTeacherId.value) // 添加日志，确认ID获取成功
        return currentTeacherId.value
      }
    } else {
      console.error('未找到用户ID')
    }
  } catch (error) {
    console.error('获取当前教师ID错误:', error)
  }
  return null
}

// 获取专利列表
const fetchPatentList = async () => {
  loading.value = true
  try {
    const params = {}
    
    // 管理员或审核员可以按条件筛选
    if (!isTeacher.value) {
      params.teacherName = searchForm.teacherName
      params.name = searchForm.name
      params.type = searchForm.type
      params.authorizationNumber = searchForm.authorizationNumber
      params.status = searchForm.status
    }
    
    const response = await axios.post('http://localhost:8081/api/patent/list', params)
    if (response.data.code === 200) {
      // 处理返回的数据结构
      if (response.data.data && Array.isArray(response.data.data)) {
        let allPatents = response.data.data.map(item => ({
          id: item.patent.id,
          teacherId: item.patent.teacherId,
          teacherName: item.teacherName,
          departmentName: item.departmentName,
          name: item.patent.name,
          type: item.patent.type,
          authorizationNumber: item.patent.authorizationNumber, // 使用正确的字段名
          applicationDate: item.patent.applicationDate,
          authorizationDate: item.patent.authorizationDate,
          status: item.patent.status
        }));
        
        // 如果是教师角色，在前端筛选当前教师的专利
        if (isTeacher.value && currentTeacherId.value) {
          patentList.value = allPatents.filter(patent => patent.teacherId === currentTeacherId.value);
          console.log('筛选后的专利数量:', patentList.value.length);
        } else {
          patentList.value = allPatents;
        }
      } else {
        patentList.value = [];
      }
    } else {
      ElMessage.error(response.data.msg || '获取专利列表失败')
    }
  } catch (error) {
    console.error('获取专利列表错误:', error)
    ElMessage.error('获取专利列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}


// 获取教师列表（用于下拉选择）
const fetchTeacherOptions = async () => {
  // 如果是教师角色，不需要获取教师列表
  if (isTeacher.value) return
  
  try {
    const response = await axios.post('http://localhost:8081/api/teacher/list', {})
    if (response.data.code === 200) {
      teacherOptions.value = response.data.data.map(item => ({
        id: item.teacher.id,
        realName: item.user.realName,
        department: item.teacher.department
      }))
    } else {
      ElMessage.error(response.data.msg || '获取教师列表失败')
    }
  } catch (error) {
    console.error('获取教师列表错误:', error)
    ElMessage.error('获取教师列表失败，请检查网络连接')
  }
}

// 搜索专利
const handleSearch = () => {
  fetchPatentList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchPatentList()
}

// 添加专利
const handleAddPatent = () => {
  dialogType.value = 'add'
  resetPatentForm()
  
  // 如果是教师角色，自动设置教师ID
  if (isTeacher.value && currentTeacherId.value) {
    patentForm.teacherId = currentTeacherId.value
  }
  
  dialogVisible.value = true
}

// 编辑专利
const handleEditPatent = (row) => {
  dialogType.value = 'edit'
  patentForm.id = row.id
  patentForm.teacherId = row.teacherId
  patentForm.name = row.name
  patentForm.type = row.type
  patentForm.authorizationNumber = row.authorizationNumber
  patentForm.authorizationDate = row.authorizationDate
  patentForm.status = row.status
  
  dialogVisible.value = true
}

// 重置专利表单
const resetPatentForm = () => {
  if (patentFormRef.value) {
    patentFormRef.value.resetFields()
  }
  
  patentForm.id = null
  patentForm.teacherId = ''
  patentForm.name = ''
  patentForm.type = ''
  patentForm.authorizationNumber = ''
  patentForm.authorizationDate = ''
  patentForm.status = 'pending'
}

// 提交专利表单
const submitPatentForm = () => {
  // 如果是教师角色，确保使用当前教师ID和待审核状态
  if (isTeacher.value && currentTeacherId.value) {
    patentForm.teacherId = currentTeacherId.value
    patentForm.status = 'pending' // 教师提交的专利始终为待审核状态
  }
  
  patentFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const url = dialogType.value === 'add' 
          ? 'http://localhost:8081/api/patent/add' 
          : 'http://localhost:8081/api/patent/update'
        
        const response = await axios.post(url, {
          id: patentForm.id,
          teacherId: patentForm.teacherId,
          name: patentForm.name,
          type: patentForm.type,
          authorizationNumber: patentForm.authorizationNumber,
          authorizationDate: patentForm.authorizationDate,
          status: patentForm.status
        })
        
        if (response.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加专利成功' : '编辑专利成功')
          dialogVisible.value = false
          fetchPatentList() // 刷新列表
        } else {
          ElMessage.error(response.data.msg || (dialogType.value === 'add' ? '添加专利失败' : '编辑专利失败'))
        }
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加专利错误:' : '编辑专利错误:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加专利失败，请检查网络连接' : '编辑专利失败，请检查网络连接')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除专利
const handleDeletePatent = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除专利 "${row.name}" 吗？此操作将不可逆！`,
      '删除专利',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const params = new URLSearchParams()
    params.append('id', row.id)
    
    const response = await axios.post('http://localhost:8081/api/patent/delete', params)
    
    if (response.data.code === 200) {
      ElMessage.success('删除专利成功')
      fetchPatentList() // 刷新列表
    } else {
      ElMessage.error(response.data.msg || '删除专利失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除专利错误:', error)
      ElMessage.error('删除专利失败，请检查网络连接')
    }
  }
}

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 先获取教师ID
    if (isTeacher.value) {
      await fetchCurrentTeacherId()
      console.log('页面加载时获取到的教师ID:', currentTeacherId.value)
    }
    
    // 获取专利列表
    await fetchPatentList()
    
    // 如果不是教师角色，获取教师选项
    if (!isTeacher.value) {
      await fetchTeacherOptions()
    }
  } catch (error) {
    console.error('页面初始化错误:', error)
  }
})
</script>

<style scoped>
.patent-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-top: 15px;
}

.list-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__row:hover td) {
  background-color: #f5f7fa;
}
</style>